from flask import Flask, request, render_template, jsonify, redirect, url_for, session
from routes import resource_bp, search_bp
from routes.translate import translate_bp
import os
from functools import wraps
import ssl

app = Flask(__name__)
app.secret_key = 'your-secret-key'
app.debug = True

# 用户数据
USERS = {
    'admin': 'admin'
}

# 登录验证装饰器
def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'username' not in session:
            return redirect(url_for('login'))
        return f(*args, **kwargs)
    return decorated_function

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        
        if username in USERS and USERS[username] == password:
            session['username'] = username
            return redirect(url_for('index'))
        else:
            return render_template('login.html', error='用户名或密码错误')
    
    return render_template('login.html')

@app.route('/logout')
def logout():
    session.pop('username', None)
    return redirect(url_for('login'))

@app.route('/')
@login_required
def index():
    """重定向到资源管理页面"""
    return redirect(url_for('resource.index'))

def register_blueprints(app):
    """注册蓝图"""
    from routes import resource_bp, search_bp  # 添加 search_bp
    app.register_blueprint(resource_bp)
    app.register_blueprint(search_bp)  # 注册搜索蓝图
    app.register_blueprint(translate_bp, url_prefix='/translate')

# 创建必要的目录
os.makedirs('static/uploads', exist_ok=True)
os.makedirs('workspace/data', exist_ok=True)

# 注册蓝图
register_blueprints(app)

if __name__ == '__main__':
    # 在本地开发时使用 localhost
    app.run(host='localhost', port=5000, debug=True) 